﻿#ifndef DYNBASE_H
#define DYNBASE_H
#include <string>
 
class Object;
class ClassInfo;
 
typedef Object* (*ObjectConstructorFn)(void); 
bool Register(ClassInfo* ci);
using namespace std;
/**
  *
  * @brief 这个相当于QT的MetaObject，只是QT有Moc解析，只需通过Q_OBJECT声明即可
  *        但是这里却需要DECLARE_CLASS声明和IMPLEMENT_CLASS定义
*/
class ClassInfo
{
public:
    ClassInfo(const std::string className,ObjectConstructorFn ctor)
    :m_className(className) ,m_objectConstructor(ctor)
    {
        Register(this);
    }
    virtual ~ClassInfo(){}
    Object* CreateObject()const
    {
        return m_objectConstructor ? (*m_objectConstructor)() : nullptr;
    }
    bool IsDynamic()const
    {
        return nullptr != m_objectConstructor;
    }
    const std::string GetClassName()const
    {
        return m_className;
    }
    ObjectConstructorFn GetConstructor()const
    {
        return m_objectConstructor;
    }

public:
    string m_className;
    ObjectConstructorFn m_objectConstructor;
};

#define DECLARE_CLASS_INHERIT(name) \
    protected: \
        static ClassInfo ms_classinfo; \
    public:  \
        virtual ClassInfo* GetClassInfo() const; \
        static Object* CreateObject(); \

#define IMPLEMENT_CLASS_INHERIT(name)            \
    ClassInfo name::ms_classinfo((#name), \
             static_cast<ObjectConstructorFn>(name::CreateObject)); \
               \
    ClassInfo *name::GetClassInfo() const \
        {return &name::ms_classinfo;}\
               \
    Object* name::CreateObject() \
        { return new name;}

class Object
{
    DECLARE_CLASS_INHERIT(Object) //Object也可以反射生成
public:
    Object(){}
    virtual ~Object(){}
    static bool Register(ClassInfo* ci);
    static Object* MakeObject(string name);
};
 
 
#endif
